package com.clkj.cldisabledmanclient.mvp.homerecovertrain;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.clkj.cldisabledmanclient.R;
import com.clkj.cldisabledmanclient.adapter.GalleryAdapter;
import com.clkj.cldisabledmanclient.adapter.PhotoAdapter;
import com.clkj.cldisabledmanclient.base.BaseActivity;
import com.clkj.cldisabledmanclient.constant.ShareKey;
import com.clkj.cldisabledmanclient.http.HttpConfig;
import com.clkj.cldisabledmanclient.http.TwitterRestClient;
import com.clkj.cldisabledmanclient.mvp.SuccessActivity;
import com.clkj.cldisabledmanclient.mvp.recovertrainapply.AddKfxlApplyFileActivity;
import com.clkj.cldisabledmanclient.util.CommonUtil;
import com.clkj.cldisabledmanclient.util.MyGlideEngine;
import com.clkj.cldisabledmanclient.util.ToastUtil;
import com.clkj.cldisabledmanclient.widget.MyTextView;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cz.msebera.android.httpclient.Header;

public class SubmitHomeTrainActivity extends BaseActivity {

    private MyTextView tvDateTimeLabel;
    private MyTextView tvDateTime;
    private ImageView ivAdd;
    private RecyclerView rvPhotos;
    private TextView tvSubmit;

    private int REQUST_ADD_PICTURE = 0x11;
    private List<Uri> uriList = new ArrayList<>();
    private List<String> imgPathList = new ArrayList<>();

    private GalleryAdapter photoAdapter;

    private String type;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit_home_train);
        initTitle(null, null, "居家康复训练", true, null);

        initView();
        initData();
        assignView();
    }

    @Override
    public void initData() {

        //配置recycleview
        GridLayoutManager llManager = new GridLayoutManager(this, 3);
        //LinearLayoutManager llManager = new LinearLayoutManager(this);
        llManager.setOrientation(LinearLayoutManager.VERTICAL);
        //解决scrollview和recycleview嵌套滑动冲突
        llManager.setSmoothScrollbarEnabled(true);
        llManager.setAutoMeasureEnabled(true);

        rvPhotos.setLayoutManager(llManager);
        rvPhotos.setNestedScrollingEnabled(false);
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        rvPhotos.setHasFixedSize(true);

        photoAdapter = new GalleryAdapter(imgPathList, this);
        rvPhotos.setAdapter(photoAdapter);
        rvPhotos.setHasFixedSize(true);

        type = getIntent().getStringExtra("type");
    }

    @Override
    public void assignView() {

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //System.out.println(dateFormat.format(date));
        tvDateTime.setText(dateFormat.format(date));

        //提交图片
        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Dexter.withActivity(SubmitHomeTrainActivity.this)
                        .withPermissions(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .withListener(new MultiplePermissionsListener() {
                            @Override
                            public void onPermissionsChecked(MultiplePermissionsReport report) {
                                /* ... */
                                if (report.areAllPermissionsGranted()) {
                                    chooseImg(REQUST_ADD_PICTURE);
                                } else {

                                    ToastUtil.showShort(SubmitHomeTrainActivity.this, "我们需要获取相关权限保证App的正常运行，请去设置界面进行相关设置");
                                }
                            }

                            @Override
                            public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                                /* ... */
                                token.continuePermissionRequest();
                            }
                        }).check();

            }
        });

        //提交居家康复开始
        tvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (imgPathList.size() == 0) {
                    ToastUtil.showShort(SubmitHomeTrainActivity.this, "请先上传训练图片");
                    return;
                }
                showLoading();
                RequestParams params = new RequestParams();
                String idCard = (String) CommonUtil.getShareValue(ShareKey.USER_IDCARD, "");
                String name = (String) CommonUtil.getShareValue(ShareKey.USER_NAME, "");
                Date date = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String nowTime = dateFormat.format(date);
                params.put("IdCard", idCard);
                params.put("name", name);
                params.put("eventTime", nowTime);
                params.put("state", type);

                List<File> fileList = new ArrayList<>();
                for (int j = 0; j < imgPathList.size(); j++) {
                    fileList.add(new File(imgPathList.get(j)));
                }
                try {
                    File[] files = fileList.toArray(new File[0]);
                    params.put("homeEnclosure", files);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                TwitterRestClient.postByAbsoluteUrl(HttpConfig.URL_OF_INTERFACE_BASE + "CDPFIN/submitAttendanceHome", params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                        Log.e("提交", new String(responseBody));
                        dismissLoading();
                        if (statusCode == 200) {
                            ToastUtil.showShort(SubmitHomeTrainActivity.this, "提交康复训练成功");
                            startActivity(new Intent(SubmitHomeTrainActivity.this, SuccessActivity.class));
                            finish();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                        Log.e("提交失败", error.getMessage());
                        dismissLoading();
                        ToastUtil.showShort(SubmitHomeTrainActivity.this, "提交失败，请重试");
                    }
                });

            }
        });
    }


    private void chooseImg(int requesttype) {

        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .capture(true)
                .captureStrategy(
                        new CaptureStrategy(true, "com.clkj.cldisabledmanclient.fileprovider"))
                .maxSelectable(6)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.60f)
                .imageEngine(new MyGlideEngine())
                .forResult(requesttype);
    }

    @Override
    public void initView() {

        tvDateTimeLabel = (MyTextView) findViewById(R.id.tv_dateTime_label);
        tvDateTime = (MyTextView) findViewById(R.id.tv_dateTime);
        ivAdd = (ImageView) findViewById(R.id.iv_add);
        rvPhotos = (RecyclerView) findViewById(R.id.rv_photos);
        tvSubmit = (TextView) findViewById(R.id.tv_submit);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //mSelectedImgAttachment = Matisse.obtainResult(data);
        if (resultCode == RESULT_OK) {
            //获取返回的图片数据
            if (requestCode == REQUST_ADD_PICTURE) {
                //Uri uri = Matisse.obtainResult(data).get(0);
                //String grzpPath = Matisse.obtainPathResult(data).get(0);
                imgPathList.clear();
                uriList = Matisse.obtainResult(data);
                List<String> fileList = Matisse.obtainPathResult(data);
                imgPathList.addAll(fileList);
                photoAdapter.notifyDataSetChanged();
            }
        }
    }

    public void showLoading() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(true);
            //设置点击进度对话框外的区域对话框不消失
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setMessage("正在加载" +
                    "...");
            progressDialog.show();
        }
    }

    public void dismissLoading() {
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }
}
